const state = {
  versions: [],
  currentVersion: null,
  versionHistory: [],
  versionTags: []
}

const mutations = {
  SET_VERSIONS(state, versions) {
    state.versions = versions
  },
  SET_CURRENT_VERSION(state, version) {
    state.currentVersion = version
  },
  ADD_VERSION(state, version) {
    state.versions.push(version)
  },
  UPDATE_VERSION(state, { id, updates }) {
    const index = state.versions.findIndex(v => v.id === id)
    if (index !== -1) {
      state.versions[index] = { ...state.versions[index], ...updates }
    }
  },
  ADD_VERSION_HISTORY(state, history) {
    state.versionHistory.push(history)
  },
  SET_VERSION_TAGS(state, tags) {
    state.versionTags = tags
  }
}

const actions = {
  async createVersion({ commit }, { templateId, versionData, description }) {
    const newVersion = {
      id: Date.now(),
      templateId,
      version: versionData.version || '1.1',
      content: versionData.structuredContent,
      description,
      createTime: new Date().toISOString(),
      author: '系統',
      status: 'active',
      tags: versionData.tags || []
    }
    
    commit('ADD_VERSION', newVersion)
    
    // 記錄版本歷史
    const history = {
      id: Date.now(),
      versionId: newVersion.id,
      action: 'create',
      description: `創建版本 ${newVersion.version}`,
      timestamp: new Date().toISOString(),
      user: '系統'
    }
    commit('ADD_VERSION_HISTORY', history)
    
    return newVersion
  },
  
  async updateVersion({ commit }, { versionId, updates }) {
    commit('UPDATE_VERSION', { id: versionId, updates })
    
    // 記錄更新歷史
    const history = {
      id: Date.now(),
      versionId,
      action: 'update',
      description: '更新版本內容',
      timestamp: new Date().toISOString(),
      user: '系統'
    }
    commit('ADD_VERSION_HISTORY', history)
  },
  
  async rollbackVersion({ commit }, { versionId, targetVersionId }) {
    const targetVersion = state.versions.find(v => v.id === targetVersionId)
    if (targetVersion) {
      commit('UPDATE_VERSION', { 
        id: versionId, 
        updates: { 
          content: targetVersion.content,
          rollbackFrom: targetVersionId,
          rollbackTime: new Date().toISOString()
        } 
      })
      
      // 記錄回滾歷史
      const history = {
        id: Date.now(),
        versionId,
        action: 'rollback',
        description: `回滾到版本 ${targetVersion.version}`,
        timestamp: new Date().toISOString(),
        user: '系統'
      }
      commit('ADD_VERSION_HISTORY', history)
    }
  },
  
  async compareVersions({ state }, { versionId1, versionId2 }) {
    const version1 = state.versions.find(v => v.id === versionId1)
    const version2 = state.versions.find(v => v.id === versionId2)
    
    if (version1 && version2) {
      return {
        version1,
        version2,
        differences: generateDifferences(version1.content, version2.content)
      }
    }
    return null
  }
}

const getters = {
  getVersionById: (state) => (id) => {
    return state.versions.find(v => v.id === id)
  },
  getVersionsByTemplate: (state) => (templateId) => {
    return state.versions.filter(v => v.templateId === templateId)
  },
  getActiveVersions: (state) => {
    return state.versions.filter(v => v.status === 'active')
  },
  getVersionHistory: (state) => (versionId) => {
    return state.versionHistory.filter(h => h.versionId === versionId)
  },
  getLatestVersion: (state) => (templateId) => {
    const versions = state.versions.filter(v => v.templateId === templateId)
    if (versions.length > 0) {
      return versions.sort((a, b) => new Date(b.createTime) - new Date(a.createTime))[0]
    }
    return null
  }
}

// 生成版本差異
function generateDifferences(content1, content2) {
  const differences = {}
  
  // 比較各個字段
  Object.keys(content1).forEach(key => {
    if (content2[key]) {
      if (Array.isArray(content1[key]) && Array.isArray(content2[key])) {
        if (JSON.stringify(content1[key]) !== JSON.stringify(content2[key])) {
          differences[key] = {
            type: 'array',
            old: content1[key],
            new: content2[key]
          }
        }
      } else if (content1[key] !== content2[key]) {
        differences[key] = {
          type: 'string',
          old: content1[key],
          new: content2[key]
        }
      }
    } else {
      differences[key] = {
        type: 'deleted',
        old: content1[key],
        new: null
      }
    }
  })
  
  // 檢查新增的字段
  Object.keys(content2).forEach(key => {
    if (!content1[key]) {
      differences[key] = {
        type: 'added',
        old: null,
        new: content2[key]
      }
    }
  })
  
  return differences
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}